//
// Created by papupupu on 12/25/2022.
//

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

#define MAXSIZE 36
#define ONE '1'
#define ZERO '0'

void prime(int readfd, int writefd);


int
main(int argc, char *args) {
    int pid, fd[2];
    if (pipe(fd) < 0) printf("pipe error!");
    pid = fork();

    if (pid < 0) printf("fork error!");

    else if (pid > 0) {
        char nums[MAXSIZE];
        nums[0] = nums[1] = ZERO;
        write(fd[1], nums, MAXSIZE);
        wait((int *) 0);
        exit(0);
    } else if (pid == 0) {
        prime(fd[0],fd[1]);
    }
    exit(0);
}

void prime(int readfd, int writefd) {
    char nums[MAXSIZE];
    read(readfd, nums, MAXSIZE);

    int i = 0, val;
    while (nums[i]=='0' && i<=MAXSIZE) ++i;
    if(i== MAXSIZE && !nums[i]) return;

    val = i;
    printf("prime: %d\n", val);
    for(int j = i; j <= MAXSIZE; j+=i)
        nums[j]=ZERO;

    int pid = fork();
    if(pid == 0){
        prime(readfd,writefd);
    }
    else if(pid > 0){
        write(writefd,nums,MAXSIZE);
        wait((int*) 0);
        exit(0);
    }
    exit(0);
}

